package ${package.Stereotype}.advice;

import ${package.Stereotype}.exception.APIException;
import ${package.Stereotype}.vo.ResultCode;
import ${package.Stereotype}.vo.ResultVo;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * spring boot 全局异常处理,统一返回 {@linkplain ResultVo 返回对象}
 */
@RestControllerAdvice
public class ControllerExceptionAdvice {

    @ExceptionHandler({BindException.class})
    public ResultVo MethodArgumentNotValidExceptionHandler(BindException e){
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResultVo(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    @ExceptionHandler({APIException.class})
        public ResultVo MethodApiExceptionHandler(APIException e){
        return new ResultVo(e.getCode(), e.getMsg(), e.getMessage());
    }

    @ExceptionHandler({Exception.class})
    public ResultVo MethodExceptionHandler(Exception e){
        e.printStackTrace();
        return new ResultVo(ResultCode.NETERROR, "");
    }

}
